#coding:utf-8

import urllib,urllib2
import cookielib
import damatu
import ssl
import json
import re
from json import loads
from cons import  station_names
import time
ssl._create_default_https_context= ssl._create_unverified_context
c = cookielib.LWPCookieJar()#生成一个储存cookie的对象
cookie = urllib2.HTTPCookieProcessor(c)
opener = urllib2.build_opener(cookie)
urllib2.install_opener(opener)
secretStr=''
city = {}
headers={
'Referer':'https://kyfw.12306.cn/otn/leftTicket/init',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',
}
getheaders={
'Referer':'https://kyfw.12306.cn/otn/leftTicket/init',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',
'Cookie':'JSESSIONID=894A81AA96C2604537DE90D8486A362F; tk=QAC1caSGpLB_hMZ-UNUiye5u3Zvnk1q3f9eqgvlLtVUy01110; RAIL_OkLJUJ=FDqkp7rjB5m93OENiXPH9mh8rRO32t7w; fp_ver=4.5.1; RAIL_EXPIRATION=1505045872519; RAIL_DEVICEID=JTE4-_zm3jSNKC1Pgfee1ZOBLf-IV-mqVCZXpG7fE2GCu_O0yzd_DDw0ibwsT05YdrRYWDwMzG7s26M61r9QPdzthhS_4F2DlgtfaTmV0963E_zCMLwykLtcRSbGfo1Hdd19ifcYwT7M6kwL1L89NiVaa5_RRWhJ; _jc_save_showIns=true; route=c5c62a339e7744272a54643b3be5bf64; BIGipServerpool_passport=250413578.50215.0000; BIGipServerotn=1373176074.64545.0000; BIGipServerpassport=803733770.50215.0000; current_captcha_type=Z; _jc_save_fromStation=%u4E0A%u6D77%2CSHH; _jc_save_toStation=%u676D%u5DDE%2CHZH; _jc_save_fromDate=2017-10-17; _jc_save_toDate=2017-10-11; _jc_save_wfdc_flag=dc',
}

for i in station_names.split('@'):
    if not i:
        continue
    tem_list = i.split('|')
    city[tem_list[1]] = tem_list[2]
#print city
tk = raw_input("请输入出发地点")
ar = raw_input("请输入到达地点")
from_station = tk  #出发站
to_station = ar    #终点站
train_date = '2017-10-17'#出发日期
seat ='二等座'
#请求验证码图片
def getCode():   #获取验证码
    req = urllib2.Request('https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand&0.6758497665429419')
    req.headers = headers
    codeimg = opener.open(req).read()
    fn = open('code.png','wb')
    fn.write(codeimg)
    fn.close()
def code():  #校验验证码
    getCode()
    req = urllib2.Request('https://kyfw.12306.cn/passport/captcha/captcha-check')
    req.headers = headers
    #codeinput = raw_input('>>')
    codeinput = damatu.codeCal()
    print codeinput
    data= {

        'answer':codeinput,
        'login_site':'E',
        'rand':'sjrand',
    }
    data = urllib.urlencode(data)#把字点类型数据转换成查询字符串
    html = opener.open(req,data=data).read()
    result = json.loads(html)
    if result['result_code'] == '4':
        print '验证码校验成功'
        return True
    else:
        print '验证码校验失败,正在重新执行'
        code()

def login():
    req = urllib2.Request('https://kyfw.12306.cn/passport/web/login')
    data = {
        'username': '15764230482',
        'password': 'yf296349469',
        'appid': 'otn'
    }
    data = urllib.urlencode(data)
    html = opener.open(req, data=data).read()
    result = loads(html)
    req = urllib2.Request("https://kyfw.12306.cn/passport/web/auth/uamtk")

    # req = urllib2.Request('https://kyfw.12306.cn/passport/web/auth/uamtk')
    req.headers = headers
    html = opener.open(req, data='appid=otn').read()
    result = loads(html)
    print 000,html
    newapptk = result['newapptk']
    req = urllib2.Request('https://kyfw.12306.cn/otn/uamauthclient')
    req.headers = headers
    html = opener.open(req, data='tk=%s' % newapptk).read()
    print 333,html
    #req = urllib2.Request('https://kyfw.12306.cn/passport/web/login')
    ##username = raw_input('>>')
    ##password = raw_input('>>')
    #data = {
    #    'username':'15764230482',
    #    'password':'yf296349469',
    #    'appid':'otn'
    #}
    #req.headers = headers
    #data =urllib.urlencode(data)
    #html = opener.open(req,data).read()
    #result = loads(html)
    #request = urllib2.Request("https://kyfw.12306.cn/passport/web/auth/uamtk")
    #request.headers = headers
    #data1={
    #    'appid':'otn',
    #}
    #data1 = urllib.urlencode(data1)
    #html = opener.open(request,data=data1).read()
    #result = loads(html)
    #newapptk = result["newapptk"]
    #req = urllib2.Request("https://kyfw.12306.cn/otn/uamauthclient")
    #req.headers=headers
    #html = opener.open(req, data='tk=%s' %newapptk).read()
    #print html
    #if result['result_code']==0:
    #    print '登陆成功'
    #    return True
    #else:
    #    print '登陆失败'
def getTrain():
    req= urllib2.Request('https://kyfw.12306.cn/otn/leftTicket/log?leftTicketDTO.train_date=%s&leftTicketDTO.from_station=%s&leftTicketDTO.to_station=%s&purpose_codes=ADULT'%(train_date,city[from_station],city[to_station]))
    req.headers=headers
    html= opener.open(req).read()
    print 666,html
    #request = urllib2.Request('https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2017-10-17&leftTicketDTO.from_station=SHH&leftTicketDTO.to_station=HZH&purpose_codes=ADULT')
    request = urllib2.Request('https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=%s&leftTicketDTO.from_station=%s&leftTicketDTO.to_station=%s&purpose_codes=ADULT'%(train_date,city[from_station],city[to_station]))
    request.headers = getheaders
    html = opener.open(request).read()
    result = loads(html)
    print 111,html
    return result['data']['result']

#下单
def order(secretStr):
    #第一步
    request = urllib2.Request("https://kyfw.12306.cn/otn/login/checkUser")
    html = opener.open(request,data="_json_att:").read()
    result = loads(html)
    #print html
    #第二步
    req = urllib2.Request("https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest")
    #data={
    #    'secretStr': secretStr,
    #    'train_date':'2017 - 10 - 17',
    #    'back_train_date':'2017 - 10 - 11',
    #    'tour_flag':'dc',
    #    'purpose_codes':'ADULT',
    #    'query_from_station_name':'上海',
    #    'query_to_station_name':'杭州',
    #    'undefined':'',
    #}
    data='secretStr=%s&train_date=%s&back_train_date=%s&tour_flag=dc&purpose_codes=ADULT&query_from_station_name=%s&query_to_station_name=%s&undefined'%(secretStr,train_date,time.strftime('%Y-%m-%d'),tk,ar).decode('utf-8')
    #data = 'secretStr=%s&train_date=%s&back_train_date=%s&tour_flag=dc&purpose_codes=ADULT&query_from_station_name=%s&query_to_station_name=%s&undefined' %(secretStr,train_date,time.strftime('%Y-%m-%d'),tk,ar)
    #data = urllib.urlencode(data)
    #print 444,data
    html = opener.open(req,data=data)
    req.headers=headers
    # result = loads(html)
    print 222,html.read()
    #print html.geturl()
    req = urllib2.Request('https://kyfw.12306.cn/otn/index/initMy12306')
    req.headers = headers
    html = opener.open(req)
    print 888,html.geturl()
    #获取乘客信息
    req=urllib2.Request("https://kyfw.12306.cn/otn/confirmPassenger/initDc")
    data= {
        '_json_att':'',
    }
    req.headers=headers
    data=urllib.urlencode(data)
    html = opener.open(req,data=data).read()
    reg = r"globalRepeatSubmitToken = '(\w{32})'"
    REPEAT_SUBMIT_TOKEN = re.findall(reg,html)[0]
    print 123,html
    req = urllib2.Request("https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs")
    req.headers=headers
    data={
        '_json_att':'',
         'REPEAT_SUBMIT_TOKEN':REPEAT_SUBMIT_TOKEN,
    }
    data = urllib.urlencode(data)
    html = opener.open(req,data=data)
    print 777,html.read()
code()
login()
#查票
for i in getTrain():
    print i
    tem_list = i.split("|")
    #tem_list[3]  车次
    #tem_list[8] 出发时间
    #tem_list[9] 到达时间
    #tem_list[13]  日期
    #tem_list[26] 无座
    #tem_list[29] 硬座
    #tem_list[25] 特等座
    #tem_list[31] 一等座
    #tem_list[30] 二等座
    #tem_list[23] 软卧
    #print tem_list
    #a=0
    #for n in tem_list:
    #    print '[%s]%s'%(a,n)
    #    a+=1
    #break
    secretStr = tem_list[0]
    if tem_list[30] != u'无'and tem_list[30] != u'':
        print '有票'
        print tem_list[3], tem_list[8], tem_list[9]
        break
    else:
        print '无票'
#下单
print 999,secretStr
order(secretStr)